<script>
import request, { uploadFile, createCancelToken } from "@/api/upload";

export default {
  name: "Databoard",
  data() {
    return {
      fileCount: 0,
      totalSize: 0,
      files: [],
      pendingFiles: [], // 待上传文件
      cancelTokens: new Map(), // 存储每个文件的取消token
    };
  },
  methods: {
    dragleave(e) {
      e.preventDefault();
      e.target.classList.remove("hover");
    },
    dragenter(e) {
      e.preventDefault();
      e.target.classList.add("hover");
    },
    async drop(e) {
      e.preventDefault();
      e.target.classList.remove("hover");

      const files = e.dataTransfer.files;
      this.fileCount = files.length;
      this.totalSize = Array.from(files).reduce(
        (sum, file) => sum + file.size,
        0
      );

      // Add files to pending list
      this.pendingFiles = Array.from(files).map((file) => ({
        name: file.name,
        size: file.size,
        progress: 0,
        id: Date.now() + Math.random(),
        file: file,
      }));
    },
    removePendingFile(id) {
      this.pendingFiles = this.pendingFiles.filter((file) => file.id !== id);
      this.fileCount = this.pendingFiles.length + this.files.length;
      this.totalSize =
        this.pendingFiles.reduce((sum, file) => sum + file.size, 0) +
        this.files.reduce((sum, file) => sum + file.size, 0);
    },
    removeFile(id) {
      const cancelToken = this.cancelTokens.get(id);
      if (cancelToken) {
        cancelToken.cancel("用户取消上传");
      }
      this.files = this.files.filter((file) => file.id !== id);
      this.fileCount = this.files.length + this.pendingFiles.length;
      this.totalSize =
        this.files.reduce((sum, file) => sum + file.size, 0) +
        this.pendingFiles.reduce((sum, file) => sum + file.size, 0);
      this.cancelTokens.delete(id);
    },
    handleFileSelect(e) {
      const files = e.target.files;
      this.fileCount = files.length;
      this.totalSize = Array.from(files).reduce(
        (sum, file) => sum + file.size,
        0
      );

      // Add files to pending list
      this.pendingFiles = Array.from(files).map((file) => ({
        name: file.name,
        size: file.size,
        progress: 0,
        id: Date.now() + Math.random(),
        file: file,
      }));
      e.target.value = ""; // 清空input以便再次选择相同文件
    },

    startUpload() {
      // Move pending files to active files
      this.files = [...this.pendingFiles];
      this.pendingFiles = [];

      // Upload files
      for (const file of this.files) {
        const cancelToken = createCancelToken();
        this.cancelTokens.set(file.id, cancelToken);

        uploadFile(
          file.file,
          (progress) => {
            const index = this.files.findIndex((f) => f.id === file.id);
            this.$set(this.files[index], "progress", progress);
          },
          cancelToken.token,
          { name: "type", value: "businessLicense" }
        ).finally(() => {
          this.cancelTokens.delete(file.id);
        });
      }
    },

    clearAllFiles() {
      this.pendingFiles = [];
      this.fileCount = 0;
      this.totalSize = 0;
    },

    cancelAllUploads() {
      // 取消所有正在上传的文件
      for (const [id, cancelToken] of this.cancelTokens) {
        cancelToken.cancel("用户取消所有上传");
      }
      this.cancelTokens.clear();
    },
  },
};
</script>

<template>
  <div class="databoard-container">
    <!-- 上传框 -->
    <div
      draggable="true"
      class="uploadBox"
      @dragleave="dragleave"
      @dragenter="dragenter"
      @dragover="(e) => e.preventDefault()"
      @drop="drop"
    >
      <div>
        <i class="el-icon-upload"></i>
        <input
          type="file"
          id="upload"
          style="display: none"
          @change="handleFileSelect"
          multiple
        />
        <p>将文件拖到此处，或 <label for="upload">点击上传</label></p>
      </div>
      <!-- 上传文件信息区域 -->
      <div class="uploadInfoBox">
        <h6>文件数量：{{ fileCount }}</h6>
        <h6>总大小：{{ (totalSize / 1024 / 1024).toFixed(2) }} MB</h6>
        <el-button
          type="primary"
          size="mini"
          @click="startUpload"
          :disabled="fileCount === 0"
        >
          开始上传
        </el-button>
        <el-button
          type="danger"
          size="mini"
          @click="clearAllFiles"
          :disabled="fileCount === 0"
          style="margin-left: 10px"
        >
          清除所有
        </el-button>
        <el-button
          type="warning"
          size="mini"
          @click="cancelAllUploads"
          :disabled="files.length === 0"
          style="margin-left: 10px"
        >
          停止上传
        </el-button>
      </div>
    </div>

    <!-- 待上传文件区域 -->
    <div class="pendingFilesBox" v-if="pendingFiles.length > 0">
      <h4>待上传文件</h4>
      <div class="uploadFileBox">
        <div
          v-for="file in pendingFiles"
          :key="file.id"
          class="fileItem pending"
        >
          <div class="fileInfo">
            <span>{{ file.name }}</span>
            <span>{{ (file.size / 1024).toFixed(2) }} KB</span>
          </div>
          <i class="el-icon-close" @click="removePendingFile(file.id)"></i>
        </div>
      </div>
    </div>

    <!-- 上传文件+进度区域 -->
    <div class="uploadFileBox" v-if="files.length > 0">
      <div v-for="file in files" :key="file.id" class="fileItem">
        <div class="fileInfo">
          <span>{{ file.name }}</span>
          <span>{{ (file.size / 1024).toFixed(2) }} KB</span>
        </div>
        <el-progress
          :percentage="file.progress"
          :stroke-width="4"
          :show-text="false"
        />
        <i class="el-icon-close" @click="removeFile(file.id)"></i>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.uploadBox {
  width: 100%;
  height: 200px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

.uploadBox.hover {
  border-color: #333;
  background-color: #e6e6e6;
  color: #333;
}

.uploadBox label {
  color: #0094ff;
}

.el-icon-upload {
  font-size: 100px;
  color: rgba(0, 0, 0, 0.1);
}

.uploadFileBox {
  width: 100%;
  margin-top: 20px;
}

.fileItem {
  display: flex;
  align-items: center;
  padding: 8px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 8px;
  position: relative;
}

.fileItem.pending {
  background: #f8f8f8;
  border-color: #ddd;
}

.pendingFilesBox {
  margin-top: 20px;
}

.pendingFilesBox h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #666;
}

.fileInfo {
  flex: 1;
  display: flex;
  justify-content: space-between;
  margin-right: 20px;
}

.el-progress {
  width: 200px;
  margin-right: 20px;
}

.el-icon-close {
  cursor: pointer;
  color: #999;
  font-size: 16px;
}

.el-icon-close:hover {
  color: #f56c6c;
}

.uploadInfoBox {
  height: 30px;
  background: #cff5f1;
  border-radius: 4px;
  width: 100%;
  display: flex;
  align-items: center;

  h6 {
    color: #666;
    font-size: 12px;
    margin-left: 15px;
  }
}
</style>
